package com.bjtu.boatmq.client.producer;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.bjtu.boatmq.common.protocol.PacketSource;
import com.bjtu.boatmq.common.protocol.ResponseCode;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class MessageHandler extends SimpleChannelInboundHandler<PacketSource>{
	class SendMessage {
        public int times;
        public long time;
        // 每次要发送的数据
        public PacketSource data;
    }
	private Map<Integer,SendMessage> map = new HashMap<Integer,SendMessage>();
	public void add(int id,PacketSource ps) {
		SendMessage sm=new SendMessage();
		sm.time=System.currentTimeMillis();
		sm.times=1;
		sm.data=ps;
		map.put(id,sm);
	}
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		// TODO Auto-generated method stub
		
		ctx.executor().scheduleAtFixedRate(new Runnable() {
			@Override
			public void run() {
				Map<Integer,SendMessage> newmap = new HashMap<Integer,SendMessage>();
				if (map.size() > 0) {
					for(int k:map.keySet()) {
						SendMessage v=map.get(k);
						long t=System.currentTimeMillis();
	                	if(t-v.time>3000) {
	                		ctx.writeAndFlush(v.data);
	                		v.time=t;
	                        v.times = v.times + 1;
	                	}
	                    if (v.times < 3) {
	                        // 保留未发送三次的。
	                    	newmap.put(k, v);
	                    }
					}
	            }
	            map = newmap;
			}
			
		}, 1, 1,TimeUnit.SECONDS);
	}
	@Override
	protected void channelRead0(ChannelHandlerContext arg0, PacketSource ps) throws Exception {
		// TODO Auto-generated method stub
		map.remove(ps.getRequestId());
		if(ps.getCode()==ResponseCode.NO_ERROR) {
			System.out.println("发送成功");
    	}
    	else {
    		System.out.println("发送失败");
    	}
	}

}
